﻿using Leeder.Logger;
using LeederGlobal;
using NewAndong.Business;
using NewAndong.Comm;
using NewAndong.Handle;
using NewAndong.Model;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace NewAndong.Forms
{
    public partial class FrmMaterial2 : UIPage
    {
        bool isLoad = true;
        AutoSizeFormClass asc = new AutoSizeFormClass();
        public LogOperate LogObj => Log.GetLogger(this.GetType());
        MaterialDirectionBLL bllMaterialDirection = new MaterialDirectionBLL();
        SignalLampDirectionBLL signalLampDirectionBLL = new SignalLampDirectionBLL();
        string _TypeName;
        int _TypeId;

        /// <summary>
        /// 顺引顺建指示循环数量修改事件
        /// </summary>
        public static event Action ProjectChangeEvent;

        /// <summary>
        /// 出发链设置出发数量修改事件
        /// </summary>
        public static event Action CFLChangeEvent;


        public FrmMaterial2(string typeName,int typeId )
        {
            _TypeId = typeId;
            _TypeName = typeName;
            InitializeComponent();
        }

        private void FrmMaterial2_Load(object sender, EventArgs e)
        {
            if (!isLoad)
                return;
            isLoad = false;
            FrmMaterial.ProjectCountChangeEvent += RefreshDgv;
            FrmTransport.StartTransportCountChangeEvent += RefreshDgv;
            Init_Control();
            RefreshDgv();
        }

        private void Init_Control()
        {
            dgv.AutoGenerateColumns = false;
            dgv.AllowUserToAddRows = false;
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgv.ReadOnly = true;
            //dgv.AddColumn("序号", "ID", 5);
            dgv.AddColumn("工程名称", "MaterialName", 20);
            dgv.AddColumn("循环台数", "ProjectCount", 15);
            dgv.AddColumn("出发台数1", "StartTransportCount", 15);
            dgv.AddColumn("出发台数2", "StartTransportCount2", 15);
            dgv.AddColumn("出发台数3", "StartTransportCount3", 15);

            dgv.AddColumn("信号源标识", "SignalMark", 15);

            uiPanel2.RectColor = Color.FromArgb(235, 243, 255);
        }

        private void RefreshDgv()
        {
            var list = bllMaterialDirection.GetList(_TypeId);
            dgv.DataSource = null;
            dgv.DataSource = list.OrderBy(x => x.ID).ToList();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Edit(null,_TypeId,_TypeName);
            RefreshDgv();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }
            Edit(dgv.CurrentRow.DataBoundItem as MaterialDirectionModel);
            RefreshDgv();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }

            if (UIMessageDialog.ShowMessageDialog("确定要删除该数据吗？", UILocalize.AskTitle, true, UIStyle.Red, true, false))
            {
                var model = dgv.CurrentRow.DataBoundItem as MaterialDirectionModel;
                bllMaterialDirection.Delete(model);
                RefreshMaterial();
                RefreshDgv();
            }
        }

        private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }
            var dgv = (UIDataGridView)sender;
            Edit(dgv.CurrentRow.DataBoundItem as MaterialDirectionModel);
            RefreshDgv();
        }

        private void Edit(MaterialDirectionModel model = null, int typeId = 0, string typeName = null)
        {
            var triaGroups = GolbalVariable.TriaGroupList.Where(x => x.SignalMark == "LIP" || x.SignalMark == "TS").Select(x => x.ID).ToArray();
            var signalMarkModelList = GolbalVariable.TriaItemList.Where(s => triaGroups.Contains(s.GroupID)).ToList();
            var signalMarks = GolbalVariable.TriaItemList.Where(s => triaGroups.Contains(s.GroupID)).Select(x => x.SignalMark).ToArray();

            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            if (model != null)
            {
                option.Text = "参数设置(" + model.MaterialName + ")";
                option.AddText("MaterialName", "工程名称", model.MaterialName, true);
                option.AddInteger("ProjectCount", "循环台数", model.ProjectCount, true);
                option.AddInteger("StartTransportCount", "出发台数1", model.StartTransportCount, true);
                option.AddInteger("StartTransportCount2", "出发台数2", model.StartTransportCount2, true);
                option.AddInteger("StartTransportCount3", "出发台数3", model.StartTransportCount3, true);
                option.AddCombobox("SignalMark", "信号源标识", signalMarkModelList, "SignalMark", "SignalMark", model.SignalMark);
            }
            else
            {
                option.Text = "新增工程";
                option.AddText("MaterialName", "工程名称", null, true);
                option.AddInteger("ProjectCount", "循环台数", 0, true);
                option.AddInteger("StartTransportCount", "出发台数1", 0, true);
                option.AddInteger("StartTransportCount2", "出发台数2", 0, true);
                option.AddInteger("StartTransportCount3", "出发台数3", 0, true);
                option.AddCombobox("SignalMark", "信号源标识", signalMarks);
            }
            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                if(frm["SignalMark"]==null||frm["SignalMark"].ToString() == "-1")
                {
                    UIMessageTip.ShowOk("请选择信号源");
                    return;
                }
               
                if (model != null)
                {
                    model.MaterialName = frm["MaterialName"].ToString();
                    model.ProjectCount = int.Parse(frm["ProjectCount"].ToString());
                    model.StartTransportCount = int.Parse(frm["StartTransportCount"].ToString());
                    model.StartTransportCount2 = int.Parse(frm["StartTransportCount2"].ToString());
                    model.StartTransportCount3 = int.Parse(frm["StartTransportCount3"].ToString());
                    model.SignalMark = frm["SignalMark"].ToString();

                    var sql = string.Format("update LA_MaterialDirection set MaterialName='{0}',ProjectCount={1},StartTransportCount={2},StartTransportCount2={3},StartTransportCount3={4},SignalMark='{5}' where ID={6}",
                        model.MaterialName, model.ProjectCount, model.StartTransportCount, model.StartTransportCount2, model.StartTransportCount3,model.SignalMark, model.ID);

                    if (bllMaterialDirection.UpdateNum(sql)>0)
                    {
                        var lamp = signalLampDirectionBLL.GetModelBySignalMark(model.MaterialName);
                        if (lamp!=null)
                        {
                            lamp.LampName = model.MaterialName;
                            lamp.SignalMark = model.MaterialName;
                            lamp.TriggerCount = model.StartTransportCount;
                            var updatesql = string.Format("update LA_SignalLampDirection set LampName='{0}',SignalMark='{1}',TriggerCount={2} where ID={3}", lamp.LampName, lamp.SignalMark, lamp.TriggerCount, lamp.ID);
                            signalLampDirectionBLL.UpdateNum(updatesql);
                            CFLChangeEvent?.Invoke();
                        }
                        UIMessageTip.ShowOk("修改成功");
                        LogObj.Info("修改顺引" + typeName + "工程成功(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);

                        RefreshMaterial();
                    }
                    else
                    {
                        UIMessageBox.ShowError("修改失败！");
                        LogObj.Error("修改顺引" + typeName + "工程失败(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
                else
                {
                    model = new MaterialDirectionModel();
                    model.MaterialName = frm["MaterialName"].ToString();
                    model.ProjectCount = int.Parse(frm["ProjectCount"].ToString());
                    model.StartTransportCount = int.Parse(frm["StartTransportCount"].ToString());
                    model.StartTransportCount2 = int.Parse(frm["StartTransportCount2"].ToString());
                    model.StartTransportCount3 = int.Parse(frm["StartTransportCount3"].ToString());
                    model.SignalMark = signalMarks[int.Parse(frm["SignalMark"].ToString())];
                    model.LeftCount = 0;
                    model.TypeId = typeId;
                    model.TypeName = typeName;

                    if (bllMaterialDirection.Add(model).IsSuccess)
                    {
                        var lamp = signalLampDirectionBLL.GetModelBySignalMark(model.MaterialName);
                        if (lamp != null)
                        {
                            lamp.LampName = model.MaterialName;
                            lamp.SignalMark = model.MaterialName;
                            lamp.TriggerCount = model.StartTransportCount;
                            var sql = string.Format("update LA_SignalLampDirection set LampName='{0}',SignalMark='{1}',TriggerCount={2} where ID={4}", lamp.LampName, lamp.SignalMark, lamp.TriggerCount, lamp.ID);
                            signalLampDirectionBLL.UpdateNum(sql);
                            CFLChangeEvent?.Invoke();
                        }
                        UIMessageTip.ShowOk("新增成功");
                        LogObj.Info("新增顺引" + typeName + "工程成功(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                        RefreshMaterial();
                    }
                    else
                    {
                        UIMessageBox.ShowError("新增失败！");
                        LogObj.Error("新增顺引" + typeName + "工程失败(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
            }
            frm.Dispose();
        }


        /// <summary>
        /// 刷新工程缓存
        /// </summary>
        private void RefreshMaterial()
        {
            List<MaterialDirectionModel> materialDirectionList = bllMaterialDirection.GetModelList();
            materialDirectionList.ForEach(x => { x.UpdateTime = DateTime.Now.AddSeconds(-30);x.LastValue = 0; });
            GolbalVariable.MaterialDirectionBag = new ConcurrentBag<MaterialDirectionModel>(materialDirectionList);
            ProjectChangeEvent?.Invoke();
        }

    }
}
